#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>

#include <string>
#define MAXLINE 1024
using namespace std;
class Client{
    private:
    char *recvline;
    int bytesReceived;
    char *sendline;
    size_t LINELEN;
    public:
    int socketfd;
    struct sockaddr_in sockaddr;
    Client(const char* addr,unsigned short port,size_t LineLen){
        LINELEN=LineLen;
        recvline=(char*)malloc(LINELEN);
        sendline=(char*)malloc(LINELEN);
        socketfd = socket(AF_INET, SOCK_STREAM, 0);
        bytesReceived=0;
        memset(&sockaddr, 0, sizeof(sockaddr));
        sockaddr.sin_family = AF_INET;
        sockaddr.sin_port = htons(port);
        inet_pton(AF_INET, addr, &sockaddr.sin_addr);
    };
    ~Client(){
        free(recvline);
        free(sendline);
        close(socketfd);
    }
    bool hook(){
        if((connect(socketfd, (struct sockaddr*) &sockaddr, sizeof(sockaddr)))<0){   //连接到服务器
            printf("connect error %s errno: %d\n", strerror(errno),errno);
            return false;
        }
        return true;
    }
    bool push_raw(char *data,size_t len){
		if((send(socketfd, data, len, 0))<0){
			printf("send message error: %s errno : %d", strerror(errno), errno);
			return false;
		}
        return true;
    }
    string rev_toStr(){
		string RespStr = recvline;
        bytesReceived = recv(socketfd, recvline, MAXLINE, 0);
		RespStr = RespStr.substr(0,bytesReceived);
        return RespStr;
    }
    void unhook(){
        close(socketfd);
    }
};